<template>
	<!-- 这是一个测试页面 -->
	<view>

	</view>
</template>
<script setup>
	import mqtt from 'mqtt/dist/mqtt.js';

	import {
		ref
	} from 'vue'

	import {
		onLoad
	} from '@dcloudio/uni-app'

	const subscribe = "test001" // 订阅的主题
	const client = ref(null) // 用来存储客户端对象
	const connectionStatus = ref('') // 连接状态

	// 客户端连接函数
	const connect = () => {

		const options = {
			clientId: '1000',
			connectTimeout: 10000,
			clean: true
		}

		let mqttUrl = 'wx://39.105.14.41:1883'

		// 创建 MQTT 客户端
		client.value = mqtt.connect(mqttUrl, options)

		client.value.on('connect', (res) => {
			connectionStatus.value = '连接成功'
			uni.showToast({
				title: "连接成功",
				duration: 2000,
				icon: "none"
			})

			// 订阅主题
			client.value.subscribe(subscribe, (err) => {
				if (!err) {
					uni.showToast({
						title: "订阅成功",
						duration: 2000,
						icon: "none"
					})
				}
			})
		})

		


		client.value.on('message', (topic, message) => {
			console.log('收到消息：', topic, message.toString())
		})




		client.value.on('reconnect', () => {
			console.log("重连")
		})
	}

	// 发送消息




	// 在组件挂载时建立连接
	onLoad(() => {
		connect()

	})
</script>

<style>

</style>